<template>
  <div class="app-container">
    <!-- 顶部智能体选择区 -->
    <el-row class="mb-4">
      <el-col :span="20">
        <el-select v-model="selectedAgent" placeholder="请选择智能体" style="width: 200px">
          <el-option
            v-for="item in agentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-col>
      <el-col :span="4" class="text-right">
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </el-col>
    </el-row>

    <div class="main-content">
      <!-- 左侧：角色与目标配置区 -->
      <div class="content-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>角色与目标配置</span>
            </div>
          </template>
          <el-form :model="form" :rules="rules" ref="roleFormRef" label-width="100px" label-position="top">
            <el-form-item label="角色名称" prop="roleName" class="form-item">
              <el-input v-model="form.roleName" placeholder="如：美妆顾问小C" />
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc" class="form-item">
              <el-input v-model="form.roleDesc" type="textarea" :rows="3" placeholder="如：专注于美妆产品推荐与护肤知识解答" />
            </el-form-item>
            <el-form-item label="目标设置" prop="roleGoal" class="form-item">
                <el-input v-model="form.roleGoal" type="textarea" :rows="textareaRows" />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 中间：知识管理区 -->
      <div class="content-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>知识管理</span>
              <el-tag size="small" type="info" class="ml-2">{{ knowledgeLength }}/2000</el-tag>
            </div>
          </template>
          <el-form :model="form" :rules="rules" ref="roleFormRef" label-width="100px" label-position="top">
            <el-form-item label="知识内容" prop="knowledge" class="form-item">
              <el-input
                v-model="form.knowledge"
                type="textarea"
                :rows="knowledgeRows"
                placeholder="请输入知识内容"
                @input="updateKnowledgeLength"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 右侧：预览与调试区 -->
      <div class="content-section">
        <el-card class="box-card chat-card">
          <Chat :callback="sendMsg" :bot-name="selectedItem.name" />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue'
// 引入组件
import Chat from '../components/chat.vue'
import { listAgent } from "@/api/app-store/agent";
import { publishPrompt, getAgentPrompt } from "@/api/app-store/prompt";
import { ElMessage } from 'element-plus';
import { sendMessage } from "@/api/app-store/chat";

// 智能体选择
const selectedAgent = ref('');
const agentList = ref([]);
const selectedItem = ref({name: ''})

/** 获取智能体列表 */
function getAgentList() {
  listAgent().then(response => {
    agentList.value = response.rows;
    selectedItem.value = agentList.value[0];
    selectedAgent.value = agentList.value[0].id;
  });
}

// 监听智能体选择变化
watch(selectedAgent, async (newVal) => {
  if (newVal) {
    selectedItem.value = agentList.value.find(item => item.id === selectedAgent.value);
    const res = await getAgentPrompt(newVal);
    const promptData = res.data;
    if (!promptData) {
      form.roleName = '';
      form.roleDesc = '';
      form.roleGoal = '';
      form.knowledge = '';
      return;
    }
    form.roleName = promptData.roleName || '';
    form.roleDesc = promptData.roleDesc || '';
    form.roleGoal = promptData.target || '';
    form.knowledge = promptData.knowledge || '';
  }
});

onMounted(() => {
  calculateRows();
  window.addEventListener('resize', calculateRows);
  getAgentList();
});

// 计算textarea的行数
const textareaRows = ref(0);
const knowledgeRows = ref(0);

const calculateRows = () => {
  // 假设每行高度为21px（可根据实际情况调整）
  const lineHeight = 21;
  // 获取视窗高度并减去其他元素的高度
  const windowHeight = window.innerHeight;
  // 预留空间给其他元素（头部、边距等）
  const reservedSpace = 290;
  // 角色名称和角色描述的高度（表单项标签 + 输入框 + 间距）
  const roleNameHeight = 70; // 标签(30px) + 输入框(32px) + 间距(8px)
  const roleDescHeight = 120; // 标签(30px) + 文本框(3行*21px=63px) + 间距(27px)
  // 计算可用高度
  const availableHeight = windowHeight - reservedSpace - roleNameHeight - roleDescHeight;
  // 计算行数
  textareaRows.value = Math.floor(availableHeight / lineHeight) - 1;
  knowledgeRows.value = Math.floor((windowHeight - reservedSpace) / lineHeight);
};

// 在组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', calculateRows);
});

// 表单数据
const form = reactive({
  roleName: '',
  roleDesc: '',
  roleGoal: '',
  knowledge: ''
})

// 表单验证规则
const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
  roleGoal: [{ required: true, message: '请输入目标设置', trigger: 'blur' }]
}

// 知识库字数统计
const knowledgeLength = ref(0)
const updateKnowledgeLength = () => {
  knowledgeLength.value = form.knowledge.length
}

// 聊天相关
const chatMessages = ref([])
const currentMessage = ref('')

// 发布提示词
const handlePublish = async () => {
  if (!selectedAgent.value) {
    ElMessage.error('请选择智能体')
    return
  }
  if (!form.roleName || !form.roleDesc || !form.roleGoal) {
    ElMessage.error('请填写完整的角色配置信息')
    return
  }

  console.log('发布提示词', selectedAgent.value)
  
  const promptData = {
    roleName: form.roleName,
    roleDesc: form.roleDesc,
    target: form.roleGoal,
    knowledge: form.knowledge || '',
    name: selectedItem.value.name || '' + '的提示词',
    agentId: selectedAgent.value
  }

  try {
    await publishPrompt(promptData)
    ElMessage.success('发布成功')
  } catch (error) {
    ElMessage.error('发布失败：' + error.message)
  }
}

const sendMsg = (currentMessage, init, callback) => {
  
  if (!currentMessage || currentMessage.trim() === '') {

    ElMessage.error('请输入消息内容')
    return
  }
  if(selectedAgent.value === '') {
    ElMessage.error('请选择智能体')
    return
  }
  init(currentMessage)
  
  const response = sendMessage({
      agentId: selectedAgent.value,
      content: currentMessage,
      roleName: form.roleName || '',
      roleDesc: form.roleDesc || '',
      target: form.roleGoal || '',
      knowledge: form.knowledge || '',
    }, data => {
      callback(data)
    })
}

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.text-right {
  text-align: right;
}

.main-content {
  display: flex;
  width: 100%;
  height: calc(100vh - 140px);
  gap: 10px;
}

.content-section {
  flex: 0 0 auto;
  padding: 0 10px;
  border-right: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
}

.content-section:first-child {
  width: 400px;
}

.content-section:nth-child(2) {
  flex: 1;
}

.content-section:last-child {
  width: 640px;
  border-right: none;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.box-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
}

.chat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.message {
  margin-bottom: 16px;
  max-width: 80%;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-items: flex-end;
}

.message.ai {
  align-items: flex-start;
}

.message-content {
  padding: 12px 16px;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  word-break: break-word;
  line-height: 1.5;
}

.message.user .message-content {
  background-color: #409eff;
  color: white;
}

.chat-input {
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 4px 4px;
}
.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  padding-bottom: 8px;
}
</style>